package com.ojoin.ojoin.eb_spider.service.catchdata;



import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.joda.time.DateTime;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.ojoin.ojoin.eb_spider.domain.BankCardCheck;
import com.ojoin.ojoin.eb_spider.service.SupplyPaymentService;
import com.ojoin.ojoin.eb_spider.service.catchdata.amazon.AMAZONInstoreBefore;
import com.ojoin.ojoin.eb_spider.service.catchdata.amazon.AMAZONInstoreNow;
import com.ojoin.ojoin.eb_spider.service.catchdata.amazon.AMAZONLogin;
import com.ojoin.ojoin.eb_spider.service.catchdata.amazon.AMAZONSettlement;
import com.ojoin.ojoin.eb_spider.service.impl.ChromeWebDriverServiceimpl;
import com.ojoin.ojoin.eb_spider.service.impl.SLDataCatchBaseServiceImpl;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlSupplyInventory;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlSupplyPayment;

@Service
public class SupplierAMAZONDataCatchServiceImpl extends
		SLDataCatchBaseServiceImpl {

	@Autowired
	private AMAZONLogin login;

	@Autowired
	private AMAZONSettlement settlement;

	@Autowired
	private AMAZONInstoreNow instoreNow;

	@Autowired
	private AMAZONInstoreBefore instoreBefore;

	@Autowired
	private SupplyPaymentService paymentService;
	
	/**
	 * Amazon 1.付款金额:支付>进货对账单(结算周期之内未支付资金（60天）--单据状态为等待付款)
	 * 
	 * 1.待确认采购单(已收货金额) 2.历史采购单(金额大于零&对账单 当前一个月最近收货日期)
	 */

	private Logger log = LoggerFactory
			.getLogger(SupplierAMAZONDataCatchServiceImpl.class);

	@Override
	public boolean LoginByUserInfo(String baseUrl, String username,
			String password) throws Exception {
		int loginCount = 1; // 开始登陆 webDriver.getDriver().get(baseUrl);

		while (loginCount < verifycodeRetryCount) {

			login.init(this.getWebDriver(), username, password);

			login.run();

			if (login.islogin()) {
				return true;
			} else {
				loginCount++;
			}
		}
		return false;
	}
	
	@Override
	public String catchSupplierName() throws BusinessException {
		return this.getWebDriver().getText("id", "greetingCell");

	}

	@Override
	public BankCardCheck catchSupplierAccount() throws BusinessException {
		BankCardCheck bcc = new BankCardCheck();
		
		String checkBankAccount = "https://vendorcentral.amazon.cn/gp/vendor/members/remittance";

		this.getWebDriver().get(checkBankAccount);

		/**
		 * 取60天内的汇款单 下载，可能存在多条记录，取最后一条最新的
		 */
		DateTime cdt = new DateTime();
		String end = cdt.toString("yyyy/MM/dd");

		DateTime twoMonthAgo = cdt.minusDays(60);
		String start = twoMonthAgo.toString("yyyy/MM/dd");

		this.getWebDriver().sendKeys("id", "paymentDateRange_1", start);

		this.getWebDriver().sendKeys("id", "paymentDateRange_2", end);

		this.getWebDriver().click("id", "searchRemittancesButton");

		List<WebElement> trs = this.getWebDriver().findElements("css",
				"#dataTable > tbody > tr");

		if (null != trs && trs.size() > 0) {

			WebElement ids = this.getWebDriver().findElement(trs.get(0), "css",
					"td:nth-child(1) > a");
			this.getWebDriver().clearByJS(ids);

			String bankNum =  this.getWebDriver()
					.getText(
							"css",
							"#layout-body > tbody > tr:nth-child(2) > td > table > tbody > tr > td:nth-child(1) > p > table > tbody > tr:nth-child(3) > td.input-form-value");

			bcc.setBankNum(bankNum);
		}
		return bcc;
	}

	@Override
	public boolean getInstoreOrderData() throws IOException, Exception {
		// 无时间参数
		
		Map<String, TbSlSupplyInventory> map = this.getAssistCatchData().getStartMess().getStoreIn();

		
		List<TbSlSupplyInventory> list = new ArrayList<TbSlSupplyInventory>();

		instoreNow.init(this.getWebDriver(), this.getAssistCatchData().getStartMess().getPlatformUser());

		instoreNow.run();

		List<TbSlSupplyInventory> now = instoreNow.result();

		instoreBefore.init(this.getWebDriver(), this.getAssistCatchData().getStartMess().getPlatformUser());

		instoreBefore.run();

		List<TbSlSupplyInventory> before = instoreBefore.result();

		list.addAll(now);
		list.addAll(before);

		instoreBefore.fiter(list, map);
		
		this.getAssistCatchData().getCata().setInventoryUpdate(now);
		this.getAssistCatchData().getCata().setInstore(list);

		return true;
	}

	@Override
	public boolean getUnpayAccountData() throws BusinessException {
		List<TbSlSupplyPayment> unpayments = new ArrayList<TbSlSupplyPayment> ();
		List<TbSlSupplyPayment> payments = new ArrayList<TbSlSupplyPayment> ();
		
		// TODO
		String starttime = this.getAssistCatchData().getStartMess().getSettlementStartTime();
				
		Map<String, TbSlSupplyPayment> waitpay = this.getAssistCatchData().getStartMess().getWaitpay();
		
		Map<String, TbSlSupplyPayment> completepay = this.getAssistCatchData().getStartMess().getCompletepay();
		
		List<Map<String, String>> Timeli = getTimes(starttime,30);
		
		Iterator<Map<String, String>> it = Timeli.iterator();

		while (it.hasNext()) {
			Map<String, String> timeMap = it.next();
 
			settlement.init(this.getWebDriver(), this.getAssistCatchData().getStartMess().getPlatformUser(),
					timeMap.get("stime").replace("-", "/"), timeMap
							.get("etime").replace("-", "/"));
			
			settlement.run();
 
			settlement.result(unpayments,payments);
			 
		}
		 
		settlement.fiter(unpayments, waitpay);
		// 系统bug，已付款单据在不同的时间会变成未付款，所以排除掉已付款的未付款单据
		settlement.fiter(unpayments, completepay);
		
		List<TbSlSupplyPayment> li = paymentService.changeToPay(waitpay,payments);
		
		this.getAssistCatchData().getCata().setPayupdate(li);
		this.getAssistCatchData().getCata().setSettlement(unpayments);

		return true;
	}

	@Override
	public boolean getPayAccountData() throws BusinessException {
		// TODO:unfindeshed

		return true;
	}

	@Override
	public boolean getOutstoreOrderData() throws BusinessException {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public BankCardCheck isSupplyAccountCorrect() throws BusinessException {
		BankCardCheck bcc = new BankCardCheck();
		bcc.setCorrect(true);
		
		return bcc;
	}

	

}
